package cn.com.homeyoda.aimate.aihealth.ui.my.family;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.ADD_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.DELETE_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_FAMILY_NAME;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_MEMBER;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.library.baseAdapters.BR;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseFragment;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.MessageTitleBean;
import cn.com.homeyoda.aimate.aihealth.bean.PromptUserListBean;
import cn.com.homeyoda.aimate.aihealth.databinding.FragmentFamilyBinding;
import cn.com.homeyoda.aimate.aihealth.ui.message.MessageTitleAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.my.family.manage.AddMemberAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.my.family.manage.ManageActivity;
import cn.com.homeyoda.aimate.aihealth.ui.record.BloodOxygenRecordFragment;
import cn.com.homeyoda.aimate.aihealth.ui.record.HeartRateRecordFragment;
import cn.com.homeyoda.aimate.aihealth.ui.record.RespiratoryRateRecordFragment;
import cn.com.homeyoda.aimate.aihealth.ui.record.blood_pressure.BloodPressureRecordFragment;
import cn.com.homeyoda.aimate.aihealth.ui.record.physical_exam.PhysicalExamRecordFragment;
import cn.com.homeyoda.aimate.aihealth.utils.RxDebounceClickListener;

public class FamilyFragment extends BaseFragment<FragmentFamilyBinding, FamilyViewModel> implements View.OnClickListener {

    private MembersAdapter membersAdapter;
    private List<FamilyMembersBean.DataBean.FamilyMembers> membersList = new ArrayList<>();

    private MessageTitleAdapter messageTitleAdapter;
    private List<MessageTitleBean> titleBeanList = new ArrayList<>();

    private int mMemberPosition = 0;
    private int mCurrentPosition = -1;
    private FragmentManager mFragmentManager;
    private Map<Integer, Fragment> mFragmentMap = new HashMap<>();

    private LinearLayout llNoMember;
    private ConstraintLayout clMember;
    private MaterialDialog addMemberDialog;
    private AddMemberAdapter addMemberAdapter;
    private FamilyMembersBean.DataBean.FamilyMembers currentMember = new FamilyMembersBean.DataBean.FamilyMembers();

    @Override
    public FamilyViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FamilyViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        setLoginStatus(isLogin());
        viewModel.getMemberList();
        viewModel.getTitleData();
        initView();
    }

    private void initView() {
        binding.tvFamilyManage.setOnClickListener(this);
        binding.tvFamilyManagement.setOnClickListener(this);
        binding.btnAddMember.setOnClickListener(new RxDebounceClickListener() {
            @Override
            protected void onValidClick(View view) {
                super.onValidClick(view);
                showAddMemberDialog();
            }
        });
        mFragmentManager = getChildFragmentManager();

        initRecyclerView();
    }

    private void initRecyclerView() {

        membersAdapter = new MembersAdapter(R.layout.family_members_item, membersList);
        binding.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.setAdapter(membersAdapter);

        membersAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mMemberPosition == position) return;
            mMemberPosition = position;
            membersAdapter.setSelectPos(position);
            messageTitleAdapter.setPos(0);
            setCurrentMember(membersList.get(position));
        });

        messageTitleAdapter = new MessageTitleAdapter(R.layout.message_title_item, titleBeanList, getContext());
        binding.setLayoutManager1(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.setAdapter1(messageTitleAdapter);

        messageTitleAdapter.setOnItemClickListener((adapter, view, position) -> {
            doSelect(position);
            messageTitleAdapter.setPos(position);
        });

    }

    private void setCurrentMember(FamilyMembersBean.DataBean.FamilyMembers member) {
        currentMember = member;
        GlideLoadUtils.loadImg(binding.ivMemberAvatar, member.getAvatar(), R.mipmap.ic_member1);
        binding.tvMemberName.setText(member.getName());
        binding.tvMemberGender.setText(member.getStringSex());
        binding.tvMemberAge.setText(member.getAge());
        binding.tvMemberWeightValue.setText(member.getStringWeight());
        binding.tvMemberHeightValue.setText(member.getStringHeight());
        binding.tvMemberHistoryValue.setText(member.getChronics());
        mCurrentPosition = -1;
        doSelect(0);
    }

    private void doSelect(int position) {
        if (mCurrentPosition == position) {
            return;
        }
        Fragment oldFragment = mFragmentMap.get(mCurrentPosition);
        // Fragment newFragment = mFragmentMap.get(position);
        Fragment newFragment;
            if (position == 1) {
                newFragment = HeartRateRecordFragment.newInstance(currentMember.getFaceId());
            } else if (position == 2) {
                newFragment = BloodPressureRecordFragment.newInstance(currentMember.getFaceId());
            } else if (position == 3) {
                newFragment = BloodOxygenRecordFragment.newInstance(currentMember.getFaceId());
            } else if (position == 4) {
                newFragment = RespiratoryRateRecordFragment.newInstance(currentMember.getFaceId());
            } else {
                newFragment = PhysicalExamRecordFragment.newInstance(currentMember.getUserId(), currentMember.getFaceId());
            }
            mFragmentMap.put(position, newFragment);
        /*} else {
            if (newFragment instanceof PhysicalExamRecordFragment) {
                ((PhysicalExamRecordFragment) newFragment).updateUser(currentMember.getUserId());
            } else if (newFragment instanceof HeartRateRecordFragment) {
                ((HeartRateRecordFragment) newFragment).updateFaceId(currentMember.getFaceId());
            } else if (newFragment instanceof BloodPressureRecordFragment) {
                ((BloodPressureRecordFragment) newFragment).updateFaceId(currentMember.getFaceId());
            } else if (newFragment instanceof BloodOxygenRecordFragment) {
                ((BloodOxygenRecordFragment) newFragment).updateFaceId(currentMember.getFaceId());
            } else if (newFragment instanceof RespiratoryRateRecordFragment) {
                ((RespiratoryRateRecordFragment) newFragment).updateFaceId(currentMember.getFaceId());
            }
        }*/
        mCurrentPosition = position;
        doFragmentChanged(oldFragment, newFragment);
    }

    private void doFragmentChanged(Fragment oldFragment, Fragment newFragment) {
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if (oldFragment != null) {
            ft.detach(oldFragment);
        }
        if (newFragment != null) {
            setFragment(newFragment);
        }
        ft.commit();
    }

    public void setFragment(Fragment fragment) {
        getChildFragmentManager()
                .beginTransaction()
                .replace(R.id.fl_record_container, fragment)
                .commit();
    }

    boolean isAdd = false;
    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.memberData.observe(this, member -> {
            membersList = member.getFamilyMembers();
            if (membersList == null) return;
            int count = membersList.size();
            boolean hasMember = count > 0;
            binding.llNoData.setVisibility(hasMember ? GONE : VISIBLE);
            binding.svContainer.setVisibility(hasMember ? VISIBLE : GONE);
            binding.tvFamilyName.setText(member.getFamilyName());
            binding.tvMemberCount.setText(String.valueOf(count));
            if (hasMember) {
                int position = mMemberPosition >= count ? 0 : mMemberPosition;
                if (membersAdapter.getSelectPos() != position)
                    membersAdapter.setSelectPos(position);
                setCurrentMember(membersList.get(position));
                membersAdapter.setNewData(membersList);
            }
            doSelect(0);
        });

        viewModel.titleData.observe(this, messageTitleBeans -> {
            titleBeanList = messageTitleBeans;
            messageTitleAdapter.setNewData(titleBeanList);
        });

        LiveEventBus.get(UPDATE_FAMILY_NAME, String.class)
                .observe(this, binding.tvFamilyName::setText);

        viewModel.promptUserData.observe(this, promptUserList -> {
            if (promptUserList.isEmpty()) {
                llNoMember.setVisibility(VISIBLE);
                clMember.setVisibility(GONE);
            } else {
                llNoMember.setVisibility(GONE);
                clMember.setVisibility(VISIBLE);
                if (addMemberAdapter == null) return;
                List<PromptUserListBean.RowsBean> list = new ArrayList<>();
                for (PromptUserListBean.RowsBean rowsBean : promptUserList) {
                    if (!TextUtils.isEmpty(rowsBean.getFaceId())) {
                        list.add(rowsBean);
                    }
                }
                addMemberAdapter.setNewData(list);
            }
        });

        LiveEventBus.get(ADD_FAMILY_MEMBER, Boolean.class).observe(this, aBoolean -> {
            if (!aBoolean) return;
            viewModel.getMemberList();
            if (addMemberDialog != null) {
                addMemberDialog.dismiss();
            }
        });

        LiveEventBus.get(DELETE_FAMILY_MEMBER, Boolean.class)
                .observe(this, aBoolean -> refreshMemberList());

        LiveEventBus.get(UPDATE_MEMBER, FamilyMembersBean.DataBean.FamilyMembers.class)
                .observe(this, member -> refreshMemberList());

    }

    private void refreshMemberList() {
        viewModel.getMemberList();
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_family;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_family_manage || id == R.id.tv_family_management) {
            startActivity(new Intent(getActivity(), ManageActivity.class));
        /*} else if (id == R.id.btn_add_member) {
            showAddMemberDialog();*/
        }
    }

    private void showAddMemberDialog() {
        viewModel.getPromptUserList();

        addMemberDialog = new MaterialDialog.Builder(getContext())
                .customView(R.layout.dialog_add_family_member, false)
                .show();

        llNoMember = addMemberDialog.getView().findViewById(R.id.ll_no_member);
        clMember = addMemberDialog.getView().findViewById(R.id.cl_member);
        addMemberAdapter = new AddMemberAdapter(R.layout.add_member_item);
        RecyclerView rvFamilyMember = addMemberDialog.getView().findViewById(R.id.rv_family_member);
        rvFamilyMember.setLayoutManager(new GridLayoutManager(getContext(), 2));
        rvFamilyMember.setAdapter(addMemberAdapter);
        addMemberAdapter.setOnItemClickListener((adapter, view, position) -> {
            PromptUserListBean.RowsBean item = addMemberAdapter.getData().get(position);
            if (item != null) {
                addMemberAdapter.setSelected(position, item.getFaceId());
            }
        });

        addMemberDialog.getView().findViewById(R.id.btn_cancel).setOnClickListener(v -> addMemberDialog.dismiss());
        addMemberDialog.getView().findViewById(R.id.btn_close).setOnClickListener(v -> addMemberDialog.dismiss());
        addMemberDialog.getView().findViewById(R.id.btn_confirm).setOnClickListener(v ->
                viewModel.addFamilyMember(addMemberAdapter.getSelectedUsers()));
        if (addMemberDialog.getWindow() != null) {
            addMemberDialog.getWindow().setLayout(964, 670);
            addMemberDialog.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0));
        }
    }

    private void setLoginStatus(boolean isLogin) {
        if (isLogin) {
            binding.svContainer.setVisibility(VISIBLE);
            binding.llNoData.setVisibility(GONE);
        } else {
            binding.svContainer.setVisibility(GONE);
            binding.llNoData.setVisibility(VISIBLE);
        }
    }

}
